package controller

import (
	"02demo-iris-mysql/models"
	service2 "02demo-iris-mysql/service"
	"github.com/kataras/iris/v12/context"
	"github.com/spf13/cast"
	"log"
)

type UserController struct {
	Service service2.UserService
}

func NewUserController() *UserController {
	return &UserController{Service: service2.NewUserService()}
}

// GetList
// @Summary 获取用户信息
// @Description 获取所有用户信息
// @Tags 用户
// @Accept json
// @Produce json
// @Router /api/user [get]
func (self *UserController) GetList() (result *models.Result) {
	return self.Service.GetUserList()
}

// PostSaveUser  保存 and 修改
// @Summary      保存 and 修改
// @Description  向你说Hello
// @Tags         用户
// @Accept       json
// @Produce      json
// @Param        who  query     string  true             "人名"
// @Success      200  {string}  string  "{"msg": "hello  lixd"}"
// @Failure      400  {string}  string  "{"msg": "who    are  you"}"
// @Router       /api/user [post]
func (self *UserController) PostSaveUser(ctx context.Context) (result models.Result) {
	user := new(models.User)
	err := ctx.ReadForm(user)
	if err != nil {
		log.Println(err)
		result.Msg = "数据有错误"
		return
	}
	return self.Service.PostSaveUser(*user)
}

// 根据id查询
func (self *UserController) GetUserById(ctx context.Context) (result models.Result) {
	id := ctx.PostValue("id")
	if id == "" {
		result.Code = 400
		result.Msg = "缺少参数id"
		return
	}
	return self.Service.GetUserById(cast.ToUint(id))
}

// 根据id删除
func (self *UserController) PostDelUser(ctx context.Context) (result models.Result) {
	id := ctx.PostValue("id")
	if id == "" {
		result.Code = 400
		result.Msg = "缺少参数id"
		return
	}
	return self.Service.DelUser(cast.ToUint(id))
}
